//导入题库的数据模型
const { log } = require('console');
const { T_subjects } = require('../models/t_exam_subjects')
const { T_user_and_subject } = require('../models/T_user_and_subject')
const { T_class } = require('../models/t_class')
const { T_academy } = require('../models/T_academy')
const { T_user_and_a_c_s } = require('../models/t_user_and_a_c_s')
const { T_grade } = require('../models/t_grade')
const { T_user_a_c_s_and_Path } = require('../models/t_user_a_c_s_and_Path')
const { T_user_a_c_s_and_PeoplePath } = require('../models/t_user_a_c_s_and_PeoplePath')
const T_question_score = require('./T_question_score')
const { T_exam_target } = require('../models/t_exam_target')
const { T_exam_target_to_question } = require('../models/t_exam_target_to_question')
const { T_user_a_c_s_and_PeiPath } = require('../models/t_user_a_c_s_and_PeiPath')
const { T_user_a_c_s_and_RengPath } = require('../models/t_user_a_c_s_and_RengPath')

const XLSX = require('xlsx')

// const { T_user_and_subject } = require('../models/T_user_and_subject')

//查询全部科目信息
exports.

    getAll_subject = async (req, res) => {
        try {
            const submes = await T_subjects.findAll();
            res.json({
                "code": 200,
                "mag": "查询全部成功",
                "data": submes
            })
        } catch (error) {
            res.json({
                "code": 500,
                "msg": "查询全部失败",
            })
        }
    }



//更新科目信息
exports.updatet_subject = async (req, res) => {
    const id = req.query.id
    const subject = req.query.subject

    try {

        const [updateRows] = await T_subjects.update(
            { subject: subject },
            { where: { id } },
        );

        res.json({
            "code": 200,
            "msg": "更新成功",
        });

    }
    catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        })
    }
}

//插入科目(没有绑定用户)
exports.createt_subject = async (req, res) => {
    const body = req.body;
    try {
        const t_subject = await T_subjects.create({
            id: null,
            subject: body.subject,
        });

        const mes = await T_question_score.insertDefaultScore(t_subject.get('id'))
        if (mes) {
            console.log(mes);
            return res.json({
                "code": 500,
                "msg": mes,
            });

        }
        res.json({
            "code": 200,
            "msg": '创建成功',
            "data": t_subject,
        });
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};

//插入科目(绑定用户)
exports.createt_subject_use = async (req, res) => {
    const { subject, user_id } = req.body;
    try {
        const t_subject = await T_subjects.create({
            id: null,
            subject: subject,
        });

        if (!t_subject) {
            res.json({
                'msg': '插入失败'
            })
            return;
        }

        const subject_id = t_subject.id

        const useSubject = await T_user_and_subject.create({
            user_id: user_id,
            subject_id: subject_id,
        })

        if (useSubject) {
            res.json({
                'code': 200,
                'msg': '创建成功',
                'data': {
                    'subject': t_subject.subject,
                    'useid': useSubject.user_id
                }
            })
        }


    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};

//删除科目
exports.delete_subjectById = async (req, res) => {
    const id = req.params.id;

    try {
        const deletedRows = await T_subjects.destroy({
            where: { id: id }, // 指定要删除的行的条件
        });
        if (deletedRows > 0) {
            res.json({
                "code": 200,
                "msg": '删除成功',
            });
        } else {
            res.json({
                "code": 404,
                "msg": `不存在该科目`,
            });
        }
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};

//通过科目id来查找科目
exports.getT_subjectrById = async (req, res) => {
    const { id } = req.params;
    console.log('ID is:', id);

    try {
        const t_subject = await T_subjects.findByPk(id);//根据id查询
        if (t_subject) {
            res.json({
                "code": 200,
                "msg": "查询成功",
                "data": t_subject,
            });
        } else {
            res.json({
                "code": 404,
                "mag": `查询失败,id为${id}的科目不存在`,
            })
        };
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message
        });
    }
};

// 配置文件上传中间件，指定上传文件的目录
const multer = require('multer');
const path = require('path'); // 导入路径处理模块，用于处理文件路径
const fs = require('fs');
// var iconv = require('iconv-lite')

// 定义文件存储的配置项
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'uploads/'); // 上传文件保存的目标文件夹
    },
    filename: function (req, file, cb) {
        const originalname = file.originalname;
        const ext = path.extname(originalname); // 获取文件后缀
        const filenameWithoutExt = path.basename(originalname, ext); // 获取文件名（不带后缀）

        let newFilename = originalname;
        let counter = 1;

        // 检查是否已经存在相同文件名的文件，如果存在，则添加序号
        while (fs.existsSync(path.join('uploads/', newFilename))) {
            newFilename = `${filenameWithoutExt}(${counter})${ext}`;
            counter++;
        }

        cb(null, newFilename); // 使用新的文件名
        // cb(null, iconv.decode(newFilename, 'utf-8'));
    }
});

const upload = multer({ storage: storage }).single('file');

// exports.getuploadDocumen = async (req, res) => {
//     try {
//         upload(req, res, async (err) => {
//             if (err) {
//                 return res.status(400).json({ success: false, message: '文件上传失败', error: err.message });
//             }

//             const tikunPath = req.file.path; // 获取用户上传的文件路径
//             const originalFileName = req.file.originalname; // 获取用户上传的文件原始文件名
//             const t_user_and_a_c_s_id = req.body.t_user_and_a_c_s_id;

//             console.log(tikunPath);
//             console.log(originalFileName);
//             console.log(t_user_and_a_c_s_id);
//             // 查找是否存在相应的记录
//             let existingRecord = await T_user_a_c_s_and_Path.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

//             if (existingRecord) {
//                 // 如果存在记录，则更新路径和文件名
//                 existingRecord.Path = tikunPath;
//                 existingRecord.file_name = originalFileName;
//                 await existingRecord.save();
//             } else {
//                 // 如果不存在记录，则创建新记录
//                 await T_user_a_c_s_and_Path.create({
//                     t_user_and_a_c_s_id: t_user_and_a_c_s_id,
//                     Path: tikunPath,
//                     file_name: originalFileName
//                 });
//             }

//             res.json({ success: true, message: '文件上传成功.', data: { path: tikunPath, originalName: originalFileName } });
//         });
//     } catch (error) {
//         console.error(error);
//         res.status(500).json({ success: false, message: '文件上传失败', error: error.message });
//     }
// };

const { Beginning } = require('../models/Course outline/beginning')
// const { Class_description} = require('../models/Course outline/Class_description')
const { Class_Introduce } = require('../models/Course outline/class_Introduce')
const { Class_Target } = require('../models/Course outline/class_Target')
const { sequelize } = require('../utill/getSequelize');
const { Index_Point } = require('../models/Course outline/index_Point')
const { class_Target_AND_Point } = require('../models/Course outline/class_Target_AND_Point')//改表
const { Course_schedule } = require('../models/Course outline/course_schedule')//改表
const { Class_Teaching_methods } = require('../models/Course outline/class_Teaching_methods')
const { Class_Assessment_method } = require('../models/Course outline/class_Assessment_method')
const { Weight_Support_link_illustrate } = require('../models/Course outline/weight_Support link_illustrate')
const { Evaluation_mechanism } = require('../models/Course outline/evaluation_mechanism')
const { Evaluation_way } = require('../models/Course outline/evaluation_way')
const { Class_Target_Weight } = require('../models/Course outline/class_Target_Weight')//改表
const { Continuous_Improvement } = require('../models/Course outline/continuous_Improvement')
const { Book } = require('../models/Course outline/book')
const { Class_Content } = require('../models/Course outline/class_Content')//改表
const { Weight_Support_link } = require('../models/Course outline/weight_Support_link')//改表
const { unit_Knowledge } = require('../models/Course outline/unit_Knowledge')
const { Level_1_assessment } = require('../models/Course outline/Level_1_assessment')
const { T_exam_label } = require('../models/t_exam_label')

const xlsx = require('xlsx');

const processBeginningSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    const sheetName = '开头表'; // 工作表名称
    const worksheet = workbook.Sheets[sheetName];

    // 从工作表中获取每个字段的值，使用try-catch块处理可能出现的异常
    let code, majors, Leader, Reviewers, unit, make_time;
    try {
        code = worksheet['B2'] ? worksheet['B2'].v : null;
        majors = worksheet['B3'] ? worksheet['B3'].v : null;
        Leader = worksheet['B4'] ? worksheet['B4'].v : null;
        Reviewers = worksheet['B5'] ? worksheet['B5'].v : null;
        unit = worksheet['B6'] ? worksheet['B6'].v : null;
        make_time = worksheet['B7'] ? worksheet['B7'].v : null;
    } catch (error) {
        console.error('读取工作表字段出错:', error);
        num = 0
        // 返回文件格式错误给前端
        return num;
    }

    // 查找是否存在相应的记录
    let existingBeginning = await Beginning.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

    if (existingBeginning) {
        // 如果存在记录，则更新记录的字段值
        existingBeginning.code = code;
        existingBeginning.majors = majors;
        existingBeginning.Leader = Leader;
        existingBeginning.Reviewers = Reviewers;
        existingBeginning.unit = unit;
        existingBeginning.make_time = make_time;
        await existingBeginning.save();
    } else {
        // 如果不存在记录，则创建新记录
        await Beginning.create({
            code: code,
            majors: majors,
            Leader: Leader,
            Reviewers: Reviewers,
            unit: unit,
            make_time: make_time,
            t_user_and_a_c_s_id: t_user_and_a_c_s_id
        });
    }
};


const processSubjectDescriptionSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    const sheetName = '科目描述'; // 科目描述工作表的名称
    const worksheet = workbook.Sheets[sheetName];
    // 从工作表中获取每个字段的值
    let code1, quality, cName, eName, creAndHours, praHours, class_unit, majors1, per_class, class_com, language
    try {
        code1 = worksheet['B2'] ? worksheet['B2'].v : null;
        quality = worksheet['D2'] ? worksheet['D2'].v : null;
        cName = worksheet['B3'] ? worksheet['B3'].v : null;
        eName = worksheet['B4'] ? worksheet['B4'].v : null;
        creAndHours = worksheet['B5'] ? worksheet['B5'].v : null;
        praHours = worksheet['D5'] ? worksheet['D5'].v : null;
        class_unit = worksheet['B6'] ? worksheet['B6'].v : null;
        majors1 = worksheet['D6'] ? worksheet['D6'].v : null;
        per_class = worksheet['B7'] ? worksheet['B7'].v : null;
        class_com = worksheet['B8'] ? worksheet['B8'].v : null;
        language = worksheet['D8'] ? worksheet['D8'].v : null;
    } catch (error) {
        console.error('读取工作表字段出错:', error);
        num = 0
        // 返回文件格式错误给前端
        return num;
    }

    // 查找是否存在相应的记录
    let existingClassDescription = await Class_description.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

    if (existingClassDescription) {
        // 如果存在记录，则更新记录的字段值
        existingClassDescription.code = code1;
        existingClassDescription.quality = quality;
        existingClassDescription.cName = cName;
        existingClassDescription.eName = eName;
        existingClassDescription.creAndHours = creAndHours;
        existingClassDescription.praHours = praHours;
        existingClassDescription.class_unit = class_unit;
        existingClassDescription.majors = majors1;
        existingClassDescription.per_class = per_class;
        existingClassDescription.class_com = class_com;
        existingClassDescription.language = language;
        await existingClassDescription.save();
    } else {
        // 如果不存在记录，则创建新记录
        await Class_description.create({
            code1: code1,
            quality: quality,
            cName: cName,
            eName: eName,
            creAndHours: creAndHours,
            praHours: praHours,
            class_unit: class_unit,
            majors1: majors1,
            per_class: per_class,
            class_com: class_com,
            language: language,
            t_user_and_a_c_s_id: t_user_and_a_c_s_id
        });
    }
};



// const processClassIntroduceSheet = async (workbook, t_user_and_a_c_s_id) => {
//     const sheetNameClass_Introduce = '一、课程介绍'; // 课程介绍工作表的名称
//     const worksheetClass_Introduce = workbook.Sheets[sheetNameClass_Introduce];
//     // 从特定的单元格中获取每个字段的值
//     const content = worksheetClass_Introduce['A2'] ? worksheetClass_Introduce['A2'].v : null;
//     // 查找是否存在相应的记录
//     let existingClass_Introduce = await Class_Introduce.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });
//     if (existingClass_Introduce) {
//         // 如果存在记录，则更新记录的字段值
//         existingClass_Introduce.content = content;
//         await existingClass_Introduce.save();
//     } else {
//         // 如果不存在记录，则创建新记录
//         await Class_Introduce.create({
//             content: content,
//             t_user_and_a_c_s_id: t_user_and_a_c_s_id
//         });
//     }
// };

const processClassIntroduceSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetNameClass_Introduce = '一、课程介绍'; // 课程介绍工作表的名称
        const worksheetClass_Introduce = workbook.Sheets[sheetNameClass_Introduce];
        // 从特定的单元格中获取每个字段的值
        const content = worksheetClass_Introduce['A2'] ? worksheetClass_Introduce['A2'].v : null;
        // 查找是否存在相应的记录
        let existingClass_Introduce = await Class_Introduce.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });
        if (existingClass_Introduce) {
            // 如果存在记录，则更新记录的字段值
            existingClass_Introduce.content = content;
            await existingClass_Introduce.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Class_Introduce.create({
                content: content,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processClassTargetSheet = async (workbook, t_user_and_a_c_s_id, sub_id) => {
    let num = 1
    try {
        const sheetNameClass_Target = '二、课程目标'; // 二、课程目标表的名称
        const worksheetClass_Target = workbook.Sheets[sheetNameClass_Target];
        const courseObjectives = [];
        let rowIndex = 4;
        while (worksheetClass_Target[`A${rowIndex}`] && worksheetClass_Target[`B${rowIndex}`]) {
            const objectiveName = worksheetClass_Target[`A${rowIndex}`].v;
            const objectiveContent = worksheetClass_Target[`B${rowIndex}`].v;
            const objective = {
                target_name: objectiveName,
                target_content: objectiveContent,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id,
                sub_id: sub_id
            };
            courseObjectives.push(objective);
            rowIndex++;
        }

        await sequelize.transaction(async (t) => {

            T_exam_target_to_question.destroy({
                where: {
                    t_user_and_a_c_s_id
                }
            })

            await T_exam_target.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            //良帅开始动手

            T_exam_paper_info.destroy({
                where: {
                    t_user_and_a_c_s_id
                }
            })

            const length = courseObjectives.length
            const num = parseInt(parseInt(100 / length) / 5)
            const score = num * 5
            //良帅结束动手



            await Promise.all(courseObjectives.map(async (objective) => {
                const newTarget = await T_exam_target.create(objective, { transaction: t });
                //良帅开始动手

                T_exam_paper_info.create({
                    type: "A",
                    t_user_and_a_c_s_id,
                });

                T_exam_paper_info.create({
                    type: "B",
                    t_user_and_a_c_s_id,
                });

                T_exam_target_to_question.create({
                    t_user_and_a_c_s_id,
                    targetId: newTarget.id,
                    questionNum: num,
                    score: score,
                    paperType: "A"

                })

                T_exam_target_to_question.create({
                    t_user_and_a_c_s_id,
                    targetId: newTarget.id,
                    questionNum: num,
                    score: score,
                    paperType: "B"
                })

                // T_question_score.insertDefaultScore(t_user_and_a_c_s_id)
                //良帅结束动手
            }));
        });
        console.log("课程目标数据插入成功");
    } catch (error) {
        console.log(`课程目标的错误为：${error}`);
        num = 0;
        return num
    }
};

const processClassTargetAndPointSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '三、课程目标与毕业要求指标点的对应关系';
        const worksheet = workbook.Sheets[sheetName];
        const objectives = [];
        let rowIndex = 4;
        while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`] && worksheet[`C${rowIndex}`]) {
            const class_target_name = worksheet[`A${rowIndex}`].v;
            const index_point_name = worksheet[`B${rowIndex}`].v;
            const between = worksheet[`C${rowIndex}`].v;
            const objective = {
                class_target_name,
                index_point_name,
                between,
                t_user_and_a_c_s_id
            };
            objectives.push(objective);
            rowIndex++;
        }

        await sequelize.transaction(async (t) => {
            await class_Target_AND_Point.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Index_Point.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Promise.all(objectives.map(async (objective) => {
                await class_Target_AND_Point.create(objective, { transaction: t });
                await Index_Point.create({
                    point_name: objective.index_point_name,
                    t_user_and_a_c_s_id: objective.t_user_and_a_c_s_id
                }, { transaction: t });
            }));
        });
        console.log("数据插入成功");
    } catch (error) {
        num = 0;
        return num
    }
};

// const processClassContentSheet = async (workbook, t_user_and_a_c_s_id) => {
//     const sheetName = '四、课程内容';
//     const worksheet = workbook.Sheets[sheetName];
//     const classContentData = [];
//     let rowIndex = 3; // 从第二行开始获取数据
//     while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`] && worksheet[`C${rowIndex}`] && worksheet[`D${rowIndex}`]) {
//         const unitKnowledgeName = worksheet[`A${rowIndex}`].v;
//         const tecContent = worksheet[`B${rowIndex}`].v;
//         const tecRequest = worksheet[`C${rowIndex}`].v;
//         const classTargetName = worksheet[`D${rowIndex}`].v;
//         const classContent = {
//             unit_knowledge_name: unitKnowledgeName,
//             tec_content: tecContent,
//             tec_request: tecRequest,
//             class_target_name: classTargetName,
//             t_user_and_a_c_s_id: t_user_and_a_c_s_id
//         };
//         classContentData.push(classContent);
//         rowIndex++;
//     }
//     try {
//         await sequelize.transaction(async (t) => {
//             await Class_Content.destroy({
//                 where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
//                 transaction: t
//             });
//             await Promise.all(classContentData.map(async (content) => {
//                 await Class_Content.create(content, { transaction: t });
//             }));
//         });
//         console.log("课程内容数据插入成功");
//     } catch (error) {
//         console.error("插入课程内容数据时出错：", error);
//     }
// };

const processClassContentSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '四、课程内容';
        const worksheet = workbook.Sheets[sheetName];
        const classContentData = [];
        let rowIndex = 3; // 从第二行开始获取数据
        while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`] && worksheet[`C${rowIndex}`] && worksheet[`D${rowIndex}`]) {
            const unitKnowledgeName = worksheet[`A${rowIndex}`].v;
            const tecContent = worksheet[`B${rowIndex}`].v;
            const tecRequest = worksheet[`C${rowIndex}`].v;
            const classTargetName = worksheet[`D${rowIndex}`].v;

            // 在 T_exam_target 表中查找对应的数据
            const target = await T_exam_target.findOne({ where: { target_name: classTargetName, t_user_and_a_c_s_id: t_user_and_a_c_s_id } });
            const targetId = target ? target.id : null;

            const classContent = {
                unit_knowledge_name: unitKnowledgeName,
                tec_content: tecContent,
                tec_request: tecRequest,
                class_target_name: classTargetName,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id,
                target_id: targetId // 记录对应的 target_id
            };
            classContentData.push(classContent);
            rowIndex++;
        }

        await sequelize.transaction(async (t) => {
            await Class_Content.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Promise.all(classContentData.map(async (content) => {
                await Class_Content.create(content, { transaction: t });
            }));
        });
        console.log("课程内容数据插入成功");
    } catch (error) {
        num = 0;
        return num
    }
};

const processCourseScheduleSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '五、课程教学进度安排';
        const worksheet = workbook.Sheets[sheetName];
        const courseScheduleData = [];
        let rowIndex = 5;
        while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`] && worksheet[`C${rowIndex}`] && worksheet[`D${rowIndex}`]) {
            const unitKnowledgeName = worksheet[`A${rowIndex}`].v;
            const allTime = worksheet[`B${rowIndex}`].v;
            const theoryTime = worksheet[`C${rowIndex}`].v;
            const practiceTime = worksheet[`D${rowIndex}`].v;
            const schedule = {
                unit_knowledge_name: unitKnowledgeName,
                all_time: allTime,
                theory_time: theoryTime,
                practice_time: practiceTime,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            };
            courseScheduleData.push(schedule);
            rowIndex++;
        }

        await sequelize.transaction(async (t) => {
            await Course_schedule.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await unit_Knowledge.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Promise.all(courseScheduleData.map(async (schedule) => {
                await Course_schedule.create(schedule, { transaction: t });
                await unit_Knowledge.create({
                    content: schedule.unit_knowledge_name,
                    t_user_and_a_c_s_id: t_user_and_a_c_s_id
                }, { transaction: t });
            }));
        });
        console.log("课程教学进度安排数据插入成功");
    } catch (error) {
        num = 0;
        return num
    }
};

const processTeachingMethodsSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetNameTeachingMethods = '六、课程教学方法';
        const worksheetTeachingMethods = workbook.Sheets[sheetNameTeachingMethods];
        const content = worksheetTeachingMethods['A2'] ? worksheetTeachingMethods['A2'].v : null;


        let existingTeachingMethods = await Class_Teaching_methods.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });
        if (existingTeachingMethods) {
            existingTeachingMethods.content = content;
            await existingTeachingMethods.save();
        } else {
            await Class_Teaching_methods.create({
                content: content,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processClassAssessmentMethodSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '七、课程考核方式'; // 工作表名称
        const worksheet = workbook.Sheets[sheetName];
        // 从工作表中获取每个字段的值
        const assess_manner = worksheet['B2'] ? worksheet['B2'].v : null;
        const examination_manner = worksheet['B3'] ? worksheet['B3'].v : null;
        const examination_time = worksheet['B4'] ? worksheet['B4'].v : null;
        const content = worksheet['B5'] ? worksheet['B5'].v : null;


        // 查找是否存在相应的记录
        let existingAssessmentMethod = await Class_Assessment_method.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

        if (existingAssessmentMethod) {
            // 如果存在记录，则更新记录的字段值
            existingAssessmentMethod.assess_manner = assess_manner;
            existingAssessmentMethod.examination_manner = examination_manner;
            existingAssessmentMethod.examination_time = examination_time;
            existingAssessmentMethod.content = content;
            await existingAssessmentMethod.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Class_Assessment_method.create({
                assess_manner: assess_manner,
                examination_manner: examination_manner,
                examination_time: examination_time,
                content: content,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processWeightSupportSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '八.2';
        const worksheet = workbook.Sheets[sheetName];
        const weightSupportData = [];
        let rowIndex = 3; // 从第二行开始获取数据
        while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`] && worksheet[`C${rowIndex}`]) {
            const classTargetName = worksheet[`A${rowIndex}`].v;
            const support = worksheet[`B${rowIndex}`].v;
            const weight = worksheet[`C${rowIndex}`].v;
            const weightSupport = {
                class_target_name: classTargetName,
                suppore: support,
                weight: weight,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            };
            weightSupportData.push(weightSupport);
            rowIndex++;
        }

        await sequelize.transaction(async (t) => {
            await Weight_Support_link.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Promise.all(weightSupportData.map(async (data) => {
                await Weight_Support_link.create(data, { transaction: t });
            }));
        });
        console.log("权重支撑数据插入成功");
    } catch (error) {
        num = 0;
        return num
    }
};

const processWeightSupportLinkIllustrateSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '八.3'; // 工作表名称
        const worksheet = workbook.Sheets[sheetName];
        const content = worksheet['A3'] ? worksheet['A3'].v : null;


        // 查找是否存在相应的记录
        let existingWeightSupportLink = await Weight_Support_link_illustrate.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

        if (existingWeightSupportLink) {
            // 如果存在记录，则更新记录的字段值
            existingWeightSupportLink.content = content;
            await existingWeightSupportLink.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Weight_Support_link_illustrate.create({
                content: content,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processAssessmentMethodSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '八、课程考核成绩评定方法';
        const worksheet = workbook.Sheets[sheetName];
        const assessmentMethodData = [];
        let rowIndex = 4; // 从第二行开始获取数据
        while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`] && worksheet[`C${rowIndex}`] && worksheet[`D${rowIndex}`] && worksheet[`E${rowIndex}`]) {
            const content = worksheet[`A${rowIndex}`].v;
            const proportion = worksheet[`B${rowIndex}`].v;
            const content2 = worksheet[`C${rowIndex}`].v;
            const Point2 = worksheet[`D${rowIndex}`].v;
            const weight2 = worksheet[`E${rowIndex}`].v;
            const assessment = {
                content,
                proportion,
                content2,
                Point2,
                weight2,
                t_user_and_a_c_s_id
            };
            assessmentMethodData.push(assessment);
            rowIndex++;
        }

        await sequelize.transaction(async (t) => {
            await Level_1_assessment.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Promise.all(assessmentMethodData.map(async (assessment) => {
                await Level_1_assessment.create(assessment, { transaction: t });
            }));
        });
        console.log("课程考核成绩评定方法数据插入成功");
    } catch (error) {
        num = 0;
        return num
    }
};

const processEvaluationMechanismSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '九、课程目标达成度评价'; // 工作表名称
        const worksheet = workbook.Sheets[sheetName];
        // 从工作表中获取每个字段的值
        const agencies = worksheet['B3'] ? worksheet['B3'].v : null;
        const data = worksheet['B4'] ? worksheet['B4'].v : null;
        const cycle = worksheet['B5'] ? worksheet['B5'].v : null;


        // 查找是否存在相应的记录
        let existingEvaluationMechanism = await Evaluation_mechanism.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

        if (existingEvaluationMechanism) {
            // 如果存在记录，则更新记录的字段值
            existingEvaluationMechanism.agencies = agencies;
            existingEvaluationMechanism.data = data;
            existingEvaluationMechanism.cycle = cycle;
            await existingEvaluationMechanism.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Evaluation_mechanism.create({
                agencies: agencies,
                data: data,
                cycle: cycle,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processEvaluationWaySheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '九.2'; // 工作表名称
        const worksheet = workbook.Sheets[sheetName];
        // 从工作表中获取每个字段的值
        const one = worksheet['B2'] ? worksheet['B2'].v : null;
        const two = worksheet['B3'] ? worksheet['B3'].v : null;
        const three = worksheet['B4'] ? worksheet['B4'].v : null;


        // 查找是否存在相应的记录
        let existingEvaluationWay = await Evaluation_way.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

        if (existingEvaluationWay) {
            // 如果存在记录，则更新记录的字段值
            existingEvaluationWay.one = one;
            existingEvaluationWay.two = two;
            existingEvaluationWay.three = three;
            await existingEvaluationWay.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Evaluation_way.create({
                one: one,
                two: two,
                three: three,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processClassTargetWeightSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '十、本课程各个课程目标的权重'; // 工作表名称
        const worksheet = workbook.Sheets[sheetName];
        const objectives = [];
        let rowIndex = 4;
        while (worksheet[`A${rowIndex}`] && worksheet[`B${rowIndex}`]) {
            const class_target_name = worksheet[`A${rowIndex}`].v;
            const weights = worksheet[`B${rowIndex}`].v;
            const objective = {
                class_target_name,
                weights,
                t_user_and_a_c_s_id
            };
            objectives.push(objective);
            rowIndex++;
        }
        if (objectives.length === 0) {
            console.log("第四行及之后的行没有数据");
            return;
        }

        await sequelize.transaction(async (t) => {
            await Class_Target_Weight.destroy({
                where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id },
                transaction: t
            });
            await Promise.all(objectives.map(async (objective) => {
                await Class_Target_Weight.create(objective, { transaction: t });
            }));
        });
        console.log("数据插入成功");
    } catch (error) {
        num = 0;
        return num
    }
};

const processContinuousImprovementSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetNameContinuousImprovement = '十一、持续改进'; // 持续改进工作表的名称
        const worksheetContinuousImprovement = workbook.Sheets[sheetNameContinuousImprovement];
        // 从特定的单元格中获取每个字段的值
        const content = worksheetContinuousImprovement['A2'] ? worksheetContinuousImprovement['A2'].v : null;


        // 查找是否存在相应的记录
        let existingContinuousImprovement = await Continuous_Improvement.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

        if (existingContinuousImprovement) {
            // 如果存在记录，则更新记录的字段值
            existingContinuousImprovement.content = content;
            await existingContinuousImprovement.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Continuous_Improvement.create({
                content: content,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};

const processTextbookAndReferenceSheet = async (workbook, t_user_and_a_c_s_id) => {
    let num = 1
    try {
        const sheetName = '十二、教材和参考书目'; // 工作表名称
        const worksheet = workbook.Sheets[sheetName];
        // 从工作表中获取每个字段的值
        const t_book = worksheet['B2'] ? worksheet['B2'].v : null;
        const refer_book = worksheet['B3'] ? worksheet['B3'].v : null;
        const basis = worksheet['B4'] ? worksheet['B4'].v : null;


        // 查找是否存在相应的记录
        let existingBook = await Book.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

        if (existingBook) {
            // 如果存在记录，则更新记录的字段值
            existingBook.t_book = t_book;
            existingBook.refer_book = refer_book;
            existingBook.basis = basis;
            await existingBook.save();
        } else {
            // 如果不存在记录，则创建新记录
            await Book.create({
                t_book: t_book,
                refer_book: refer_book,
                basis: basis,
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            });
        }
    } catch (error) {
        num = 0;
        return num
    }
};


exports.getuploadDocumen = async (req, res) => {
    try {
        upload(req, res, async (err) => {
            if (err) {
                return res.status(400).json({ success: false, message: '文件上传失败', error: err.message });
            }

            const tikunPath = req.file.path; // 获取用户上传的文件路径
            const originalFileName = req.file.originalname; // 获取用户上传的文件原始文件名
            const t_user_and_a_c_s_id = req.body.t_user_and_a_c_s_id;
            const sub_id = req.body.sub_id;

            // 解析上传的 xlsx 文件内容
            const workbook = xlsx.readFile(tikunPath);



            // 处理“开头表”
            const ben = await processBeginningSheet(workbook, t_user_and_a_c_s_id);
            console.log(`开头表${ben}`);

            // 处理“科目描述”工作表
            const de = await processSubjectDescriptionSheet(workbook, t_user_and_a_c_s_id);
            console.log(`科目表示${de}`);
            // // 一“课程介绍”工作表
            const one = await processClassIntroduceSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程介绍${one}`);
            // //二、课程目标
            const two = await processClassTargetSheet(workbook, t_user_and_a_c_s_id, sub_id);
            console.log(`课程目标${two}`);
            //三、课程目标与毕业要求指标点的对应关系
            const three = await processClassTargetAndPointSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程目标与毕业要求指标点的对应关系${three}`);
            //四、课程内容 
            const four = await processClassContentSheet(workbook, t_user_and_a_c_s_id, sub_id);
            console.log(`课程内容${four}`);
            //五、课程教学进度安排
            const five = await processCourseScheduleSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程教学进度安排${five}`);
            //六、课程教学方法
            const six = await processTeachingMethodsSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程教学方法${six}`);
            //七、课程考核方式
            const senve = await processClassAssessmentMethodSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程考核方式${senve}`);
            //八、课程考核成绩评定方法
            const eight = await processAssessmentMethodSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程考核成绩评定方法${eight}`);
            //八.2
            const eightone = await processWeightSupportSheet(workbook, t_user_and_a_c_s_id);
            console.log(`八.2${eightone}`);
            //八.3
            const eightthree = await processWeightSupportLinkIllustrateSheet(workbook, t_user_and_a_c_s_id);
            console.log(`八.3${eightthree}`);
            //九、课程目标达成度评价
            const nine = await processEvaluationMechanismSheet(workbook, t_user_and_a_c_s_id);
            console.log(`课程目标达成度评价${nine}`);
            //九.2
            const ninetwo = await processEvaluationWaySheet(workbook, t_user_and_a_c_s_id);
            console.log(`九.2${ninetwo}`);
            //十、本课程各个课程目标的权重
            const ten = await processClassTargetWeightSheet(workbook, t_user_and_a_c_s_id);
            console.log(`本课程各个课程目标的权重${ten}`);
            //十一、持续改进
            const elenve = await processContinuousImprovementSheet(workbook, t_user_and_a_c_s_id);
            console.log(`持续改进${elenve}`);
            //十二、教材和参考书目
            const twelve = await processTextbookAndReferenceSheet(workbook, t_user_and_a_c_s_id);
            console.log(`教材和参考书目${twelve}`);
            // 查找是否存在相应的记录

            if (ben == 0 || de == 0 || one == 0 || two == 0 || three == 0 || four == 0 || five == 0 || six == 0 || senve == 0 || eight == 0 || eightone == 0 || eightthree == 0 || nine == 0 || ninetwo == 0 || ten == 0 || elenve == 0 || twelve == 0) {
                res.json({
                    "code": 203,
                    "msg": "上传失败，请上传正确的文件格式和完整的内容",
                });
            } else {
                let existingRecord = await T_user_a_c_s_and_Path.findOne({ where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id } });

                if (existingRecord) {
                    // 如果存在记录，则更新路径和文件名
                    existingRecord.Path = tikunPath;
                    existingRecord.file_name = originalFileName;
                    await existingRecord.save();
                    res.status(200).json({ success: true, message: '文件更新成功' });
                } else {
                    // 如果不存在记录，则创建新记录
                    await T_user_a_c_s_and_Path.create({
                        t_user_and_a_c_s_id: t_user_and_a_c_s_id,
                        Path: tikunPath,
                        file_name: originalFileName
                    });
                    res.status(200).json({ success: true, message: '文件上传成功' });
                }



            }
        });
    } catch (error) {
        console.error(error);
        res.status(500).json({ success: false, message: '文件上传失败', error: error.message });
    }
};

//人才培养
exports.getuploadPEOPLE = async (req, res) => {
    try {
        upload(req, res, async (err) => {
            if (err) {
                return res.status(400).json({ success: false, message: '文件上传失败', error: err.message });
            }

            const tikunPath = req.file.path; // 获取用户上传的文件路径
            const originalFileName = req.file.originalname; // 获取用户上传的文件原始文件名

            console.log(tikunPath);
            console.log(originalFileName);

            await T_user_a_c_s_and_PeoplePath.create({
                Path: tikunPath,
                file_name: originalFileName
            });

            res.json({ success: true, message: '文件上传成功.', data: { path: tikunPath, originalName: originalFileName } });
        });
    } catch (error) {
        console.log(error);
        res.status(500).json({ success: false, message: '文件上传失败', error: error.message });
    }
};


//培养目标
exports.getuploadPei = async (req, res) => {
    try {
        upload(req, res, async (err) => {
            if (err) {
                return res.status(400).json({ success: false, message: '文件上传失败', error: err.message });
            }

            const tikunPath = req.file.path; // 获取用户上传的文件路径
            const originalFileName = req.file.originalname; // 获取用户上传的文件原始文件名

            console.log(tikunPath);
            console.log(originalFileName);

            await T_user_a_c_s_and_PeiPath.create({
                Path: tikunPath,
                file_name: originalFileName
            });

            res.json({ success: true, message: '文件上传成功.', data: { path: tikunPath, originalName: originalFileName } });
        });
    } catch (error) {
        console.log(error);
        res.status(500).json({ success: false, message: '文件上传失败', error: error.message });
    }
};

//认证体系
exports.getuploadReng = async (req, res) => {
    try {
        upload(req, res, async (err) => {
            if (err) {
                return res.status(400).json({ success: false, message: '文件上传失败', error: err.message });
            }

            const tikunPath = req.file.path; // 获取用户上传的文件路径
            const originalFileName = req.file.originalname; // 获取用户上传的文件原始文件名

            console.log(tikunPath);
            console.log(originalFileName);

            await T_user_a_c_s_and_RengPath.create({
                Path: tikunPath,
                file_name: originalFileName
            });

            res.json({ success: true, message: '文件上传成功.', data: { path: tikunPath, originalName: originalFileName } });
        });
    } catch (error) {
        console.log(error);
        res.status(500).json({ success: false, message: '文件上传失败', error: error.message });
    }
};

//查看教学大纲
// 过滤文件名中的特殊字符
function sanitizeFileName(fileName) {
    return fileName.replace(/[^\w.-]/g, '_');
}

// 查看 文件
exports.getDocument = async (req, res) => {
    try {
        // 从请求的查询参数中获取文件路径
        const filePath = req.query.path;

        // 检查文件是否存在
        if (!fs.existsSync(filePath)) {
            // 如果文件不存在，则返回404响应
            return res.status(404).json({ success: false, message: '文件不存在' });
        }

        // 根据文件类型设置响应头
        const ext = path.extname(filePath).toLowerCase();
        if (ext !== '.pdf') {
            // 如果不是 PDF 文件，返回400响应
            return res.status(400).json({ success: false, message: '不支持预览该文件类型' });
        }

        // 设置响应头，指定浏览器解析为 PDF
        res.setHeader('Content-Type', 'application/pdf');
        // 将 PDF 文件内容发送到响应
        const fileContent = fs.readFileSync(filePath);
        res.send(fileContent);
    } catch (error) {
        console.error(error);
        // 如果发生错误，则返回500响应，并包含错误信息
        res.status(500).json({ success: false, message: '预览文件失败', error: error.message });
    }
};


//通过id来查询科目（数组形式）
exports.getSubjectName = async (req, res) => {
    try {
        // 从请求体中获取前端发送过来的数字数组
        const numbers = req.body.subjectId;

        // 存储科目名称的数组
        const subjectNames = [];

        // 逐个解析数字数组并查询对应科目的名称
        for (const number of numbers) {
            const subject = await T_subjects.findOne({
                attributes: ['subject'],
                where: {
                    id: number
                }
            });

            if (subject) {
                subjectNames.push(subject.subject);
            }
        }

        if (subjectNames.length === 0) {
            res.status(404).json({ msg: '未找到科目' });
        } else {
            res.json({
                "code": 200,
                "msg": "查询成功",
                "data": subjectNames,
            });
        }
    } catch (error) {
        console.error('Error processing request:', error);
        res.status(500).json({
            "code": 500,
            "msg": error.message
        });
    }
};



//添加课程（与教学大纲相联系）
const { Class_description } = require('../models/Course outline/Class_description')
const T_question = require('../router_handler/T_question_score');
const { T_exam_paper_info } = require('../models/t_exam_paper_info');
exports.addClass = async (req, res) => {
    try {
        // 解构前端传来的数据
        const { code, quality, cName, eName, creAndHours, praHours, class_unit, teacher_unit, classname, teacher_grade, majors, per_class, class_com, language, user_id } = req.body;

        // 查找或创建科目
        const [subject, createdSubject] = await T_subjects.findOrCreate({
            where: { subject: cName }
        });


        // 查找或创建学院
        const [academy, createdAcademy] = await T_academy.findOrCreate({
            where: { academy_name: teacher_unit }
        });

        // 查找或创建班级
        const [classObj, createdClass] = await T_class.findOrCreate({
            where: { class_name: classname }
        });

        // 查找或创建学年
        const [gread, createdgread] = await T_grade.findOrCreate({
            where: { grade_name: teacher_grade }
        });

        // 在关联表中存储用户ID、科目ID、学院ID、班级ID,学年id
        const userAndACS = await T_user_and_a_c_s.create({
            user_id: user_id,
            subject_id: subject.id,
            academy_id: academy.id,
            class_id: classObj.id,
            grade_id: gread.id
        });

        T_question_score.insertDefaultScore(userAndACS.id)


        // // 检查用户科目表是否已存在相应记录
        // let userAnd_ACS = await T_user_and_subject.findOne({
        //     where: {
        //         user_id: user_id,
        //         subject_id: subject.id,
        //     }
        // });

        // // 如果不存在则创建新记录
        // if (!userAnd_ACS) {
        //     userAnd_ACS = await T_user_and_subject.create({
        //         user_id: user_id,
        //         subject_id: subject.id,
        //     });
        // }

        // 插入班级描述数据
        const newclass = await Class_description.create({
            code,
            quality,
            cName,
            eName,
            creAndHours,
            praHours,
            class_unit,
            teacher_unit,
            teacher_grade,
            classname,
            majors,
            per_class,
            class_com,
            language,
            t_user_and_a_c_s_id: userAndACS.id
        });

        // 返回相关信息给前端
        res.json({
            'code': 200,
            'msg': 'Data created successfully',
            'data': {
                all: newclass,
                userAndACSid: userAndACS.id,
                subject: { sub_id: subject.id, sub_name: subject.subject },
                academy: { aca_id: academy.id, acs_name: academy.academy_name },
                class: { class_id: classObj.id, calss_name: classObj.class_name },
                gread: { gread_id: gread.id, gread_name: gread.grade_name },
            }
        });
    } catch (error) {
        console.error('数据插入失败:', error);
        res.status(500).json({ error: '数据插入失败' });
    }
};

//更新课程（与教学大纲相联系）
exports.updateClassDescription = async (req, res) => {
    try {
        // 解构前端传来的数据
        const { code, quality, cName, eName, creAndHours, praHours, class_unit, teacher_unit, teacher_grade, classname, majors, per_class, class_com, language, t_user_and_a_c_s_id } = req.body;


        // 根据 t_user_and_a_c_s_id 查找对应的 Class_description 数据并更新
        const classDescription = await Class_description.findOne({
            where: { t_user_and_a_c_s_id: t_user_and_a_c_s_id }
        });

        if (!classDescription) {
            return res.status(404).json({ error: '班级描述数据不存在' });
        }

        // 更新字段
        classDescription.code = code;
        classDescription.quality = quality;
        classDescription.cName = cName;
        classDescription.eName = eName;
        classDescription.creAndHours = creAndHours;
        classDescription.praHours = praHours;
        classDescription.class_unit = class_unit;
        classDescription.teacher_unit = teacher_unit;
        classDescription.teacher_grade = teacher_grade;
        classDescription.classname = classname;
        classDescription.majors = majors;
        classDescription.per_class = per_class;
        classDescription.class_com = class_com;
        classDescription.language = language;

        // 保存更新后的数据
        await classDescription.save();

        // 返回成功消息
        res.json({
            'code': 200,
            'msg': 'Data updated successfully',
            'data': classDescription
        });
    } catch (error) {
        console.error('数据更新失败:', error);
        res.status(500).json({ error: '数据更新失败' });
    }
};

//删除科目（与教学大纲相联系）
exports.deleteRecord = async (req, res) => {
    const { t_user_and_a_c_s_id } = req.query;
    try {
        // 1. 在 T_user_and_a_c_s 表中删除指定记录
        const recordToDelete = await T_user_and_a_c_s.findOne({
            where: {
                id: t_user_and_a_c_s_id
            }
        });

        if (recordToDelete) {
            // 获取 subject_id 字段的值
            const subjectId = recordToDelete.subject_id;
            const mes = T_question.deleteQuestionScore(t_user_and_a_c_s_id)
            // T_subjects.destroy({
            //     where: {
            //         id: subjectId
            //     }
            // })
            if (!mes) {
                return res.json({
                    "code": 500,
                    "msg": mes,
                });
            }
        }


        const deletedUserAndACS = await T_user_and_a_c_s.destroy({
            where: {
                id: t_user_and_a_c_s_id
            }
        });

        if (!deletedUserAndACS) {
            return res.json({
                'code': 203,
                'msg': '找不到要删除的记录'
            });
        }





        // 2. 在 Class_description 表中删除与该记录相关联的数据
        const deletedClassDescriptions = await Class_description.destroy({
            where: {
                t_user_and_a_c_s_id: t_user_and_a_c_s_id
            }
        });

        // 返回成功消息
        res.json({
            "code": 200,
            "msg": "记录删除成功"
        });
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message
        });
    }
};


exports.Get_T_user_a_c_s_and_Path = async (req, res) => {

    const { t_user_and_a_c_s_id } = req.query;

    try {
        const classes = await T_user_a_c_s_and_Path.findAll({
            where: {
                t_user_and_a_c_s_id: t_user_and_a_c_s_id,
            },
        });

        if (classes.length === 0) {
            return res.json({
                'code': 203,
                'msg': '没有对应数据'
            });
        }

        res.json({
            'code': 200,
            'msg': '查询成功',
            'data': classes
        });
    } catch (error) {
        console.error('查询数据失败:', error);
        res.json({
            'code': 500,
            'msg': '查询失败'
        });
    }

}

//查看人才培养路径
exports.Get_T_user_a_c_s_and_PeoplePath = async (req, res) => {

    try {
        const classes = await T_user_a_c_s_and_PeoplePath.findAll();

        if (classes.length === 0) {
            return res.json({
                'code': 203,
                'msg': '没有对应数据'
            });
        }

        res.json({
            'code': 200,
            'msg': '查询成功',
            'data': classes
        });
    } catch (error) {
        console.error('查询数据失败:', error);
        res.json({
            'code': 500,
            'msg': '查询失败'
        });
    }

}

//查看培养目标路径
exports.Get_T_user_a_c_s_and_PeiPath = async (req, res) => {

    try {
        const classes = await T_user_a_c_s_and_PeiPath.findAll();

        if (classes.length === 0) {
            return res.json({
                'code': 203,
                'msg': '没有对应数据'
            });
        }

        res.json({
            'code': 200,
            'msg': '查询成功',
            'data': classes
        });
    } catch (error) {
        console.error('查询数据失败:', error);
        res.json({
            'code': 500,
            'msg': '查询失败'
        });
    }

}

//查看认证体系路径
exports.Get_T_user_a_c_s_and_RengPath = async (req, res) => {

    try {
        const classes = await T_user_a_c_s_and_RengPath.findAll();

        if (classes.length === 0) {
            return res.json({
                'code': 203,
                'msg': '没有对应数据'
            });
        }

        res.json({
            'code': 200,
            'msg': '查询成功',
            'data': classes
        });
    } catch (error) {
        console.error('查询数据失败:', error);
        res.json({
            'code': 500,
            'msg': '查询失败'
        });
    }

}